package com.zhouyibike.uu.ui.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhouyibike.uu.R;

import de.greenrobot.event.EventBus;

/**
 * 倒计时控件
 * @author lyl
 *
 */
public class Countdown extends LinearLayout {
	private TextView tv_min, tv_sec, tv_hsec;
	Myhandler myhd = new Myhandler();
	private int min, sec, hsec;
	private boolean nothavemin, nothavesec, isover;

	public Countdown(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();
		LayoutInflater.from(getContext()).inflate(R.layout.countdown, this);
		initUI();
	}

	public void initUI() {
		tv_min = (TextView) findViewById(R.id.tv_min);
		tv_sec = (TextView) findViewById(R.id.tv_sec);
		tv_hsec = (TextView) findViewById(R.id.tv_hsec);
	}

	public void setTime(int min, int sec, int hsec) {
		this.min = min;
		this.sec = sec;
		this.hsec = hsec;
		if (min == 0) {
			nothavemin = true;
		}
		if (min == 0 && sec == 0) {
			nothavesec = true;
		}
		if (min < 10) {
			tv_min.setText("0" + min);
		} else {
			tv_min.setText(min + "");
		}
		if (sec < 10) {
			tv_sec.setText("0" + sec);
		} else {
			tv_sec.setText(sec + "");
		}
		if (hsec < 10) {
			tv_hsec.setText("0" + hsec);
		} else {
			tv_hsec.setText(hsec + "");
		}
		if (!isover) {
			myhd.sendEmptyMessageDelayed(0, 1000);
		}
	}

	class Myhandler extends Handler {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (hsec == 0 && !nothavesec) {
					hsec = 59;
				} else if (hsec == 0 && nothavesec) {
					isover = true;
				} else {
					hsec--;
				}
				if (hsec == 59) {
					if (sec == 0 && !nothavemin) {
						sec = 59;
					} else if (sec == 0 && nothavemin) {
						nothavesec = true;
					} else {
						sec--;
					}
				}
				if (hsec == 59 && sec == 59) {
					if (min != 0) {
						min--;
					} else {
						nothavemin = true;
					}

				}
				if(min==0&&sec==0&&hsec==0){
					isover=true;
					EventBus.getDefault().post("timeend");
				}else
					setTime(min, sec, hsec);
				break;
			}
			super.handleMessage(msg);
		}
	}
}
